package com.googlecode.allinclusive.fw.web.struts.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.googlecode.allinclusive.fw.valueobject.ResultMessageObject;
import com.googlecode.allinclusive.fw.valueobject.UserObject;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

public class SessionInterceptor extends MethodFilterInterceptor {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -2493173178702762948L;

	UserObject userObject;
	
    protected String[] ignorePattern;
	
    public void init(){
    	ignorePattern = "(.*)A1000W(.*),(.*)Z1000W.do(.*),(.*)Z3101W.do(.*),(.*)AjaxHandler.do(.*),(.*)syserr.do(.*)".split(",");
    }
    
	@Override
	public String doIntercept(ActionInvocation invocation) throws Exception {
		
		boolean ignore = false;
		
        ActionContext ac = invocation.getInvocationContext();

        HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
        String requestURI = request.getRequestURI();
        for (String p : ignorePattern) {
        	if (requestURI.matches(p)) {
        		ignore = true;
        		break;
        	}
        }
        if (ignore) {
        	return invocation.invoke();
        }
        
        HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE);
        
		if (userObject == null) {
			
			// エラーメッセージを設定します。
			ResultMessageObject resultMessage = new ResultMessageObject(requestURI, "login fail", "password error!");
			ac.getSession().put(ResultMessageObject.RESULT_MESSAGE_KEY, resultMessage);
			response.sendRedirect("syserr.do");
		}
		// TODO Auto-generated method stub
		return null;
	}
}
